﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

using TravelSite.DAL;
using TravelSite.DAL.Repositories;
using TravelSite.Entities;
using TravelSite.Code;
using System.Globalization;
using OfficeOpenXml;

namespace TravelSite.Admin.Bookings
{
    public partial class TourPage : BaseBookingPage
    {
        private DateTime? TourDate
        {
            get
            {
                DateTime? result = null;
                if (!string.IsNullOrEmpty(Request.QueryString["date"]))
                {
                    string date = Request.QueryString["date"].ToString();
                    result = new DateTime(Convert.ToInt32(date.Substring(0, 4)), Convert.ToInt32(date.Substring(4, 2)), Convert.ToInt32(date.Substring(6, 2)));
                }
                return result;
            }
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            PageName = "Bookings_Tour";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (TourDate.HasValue)
                {
                    Session["TourDate"] = TourDate.Value;
                    Response.Redirect("Tour.aspx", true);
                }
                else
                {
                    if (Session["TourDate"] != null)
                    {
                        txtFromDateFilter.Text = txtToDateFilter.Text = Convert.ToDateTime(Session["TourDate"]).ToString("d", new CultureInfo("en-US"));
                        Session["TourDate"] = null;
                    }
                }

                grid.PageSize = DefaultPageSize;
                LoadDataFromDb();
                LoadData();
                LoadPageSizes(ddlPageSizeFilter);
            }
        }

        public override void LoadData()
        {
            grid.DataSource = GridViewData;
            grid.DataBind();
        }

        protected void LoadDataFromDb()
        {
            using (var repo = RepositoryFactory.ResolveRepository<ContactRepository>())
            {
                DateTime? dateFrom = null;
                try
                {
                    if (!string.IsNullOrEmpty(txtFromDateFilter.Text))
                        dateFrom = DateTime.ParseExact(txtFromDateFilter.Text, "d", new CultureInfo("en-US"));
                }
                catch (Exception ex)
                {
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Date From not valid!'); }, 150);", true);
                    return;
                }

                DateTime? dateTo = null;
                try
                {
                    if (!string.IsNullOrEmpty(txtToDateFilter.Text))
                        dateTo = DateTime.ParseExact(txtToDateFilter.Text, "d", new CultureInfo("en-US"));
                }
                catch (Exception ex)
                {
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Date To not valid!'); }, 150);", true);
                    return;
                }

                GridData = repo.TourList(dateFrom, dateTo).ToList();
            }
        }

        protected void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grid.PageIndex = e.NewPageIndex;
            LoadData();
        }

        protected void grid_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortExpression = e.SortExpression;
            LoadData();
        }

        protected void grid_RowCommand(object sender, CommandEventArgs e)
        {

        }

        protected override void grid_RowDataBound(Object sender, GridViewRowEventArgs e)
        {
            base.grid_RowDataBound(sender, e);

            if (e.Row.RowType == DataControlRowType.Header)
            {
                GridViewRow row = e.Row;
                for (int i = 0; i < row.Cells.Count; ++i)
                {
                    TableCell cell = row.Cells[i];

                    if (row.Cells[i].Text == "Action")
                        cell.Style.Add("min-width", "70px");
                    else
                        cell.Style.Add("min-width", "150px");
                    cell.Style.Add("white-space", "nowrap");
                }
            }
            else if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (IsEmptyGrid)
                {
                    e.Row.Attributes.Add("style", "display:none;");
                    return;
                }

                Contact item = (Contact)e.Row.DataItem;

                if ((e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
                {
                    Control btn = e.Row.FindControl("btnShowTourDate");
                    TextBox tb = (TextBox)e.Row.FindControl("txtTourDate");
                    tb.Text = item.TourDate;
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "DateEditInit", string.Format("SetGridDateEdit('{0}', '{1}')", tb.ClientID, btn.ClientID), true);

                    DropDownList ddl = (DropDownList)e.Row.FindControl("ddlTourCompany");
                    using (var repo = RepositoryFactory.ResolveRepository<TourCompanyRepository>())
                    {
                        List<TourCompany> tourCompanies = repo.FindAll().ToList();
                        ddl.DataSource = tourCompanies;
                        ddl.DataBind();
                        ddl.SelectedValue = "-1";
                        if (item.TourCompanyId.HasValue)
                            ddl.SelectedValue = item.TourCompanyId.Value.ToString();
                        else
                        {
                            TourCompany defCompany = tourCompanies.FirstOrDefault(x => x.IsDefault);
                            if (defCompany != null)
                            {
                                ddl.SelectedValue = defCompany.TourCompanyId.ToString();
                            }
                        }
                    }

                    ddl = (DropDownList)e.Row.FindControl("ddlTour");
                    using (var tourRepo = RepositoryFactory.ResolveRepository<TourRepository>())
                    {
                        List<Tour> tours = new List<Tour>();
                        tours.Add(new Tour() { TourId = -1, TourName = "" });
                        tours.AddRange(tourRepo.FindAll());

                        ddl.DataSource = tours;
                        ddl.DataBind();
                        ddl.SelectedValue = "-1";
                        if (item.TourHotelId.HasValue)
                            ddl.SelectedValue = item.TourHotelId.Value.ToString();
                    }
                    
                    tb = (TextBox)e.Row.FindControl("txtTourHotelCost");
                    if (item.TourHotelCost.HasValue)
                        tb.Text = item.TourHotelCost.Value.ToString("N", new CultureInfo("en-US"));

                    tb = (TextBox)e.Row.FindControl("txtUpgradeFee");
                    if (item.UpgradeFee.HasValue)
                        tb.Text = item.UpgradeFee.Value.ToString("#,##0", new CultureInfo("en-US"));

                    tb = (TextBox)e.Row.FindControl("txtGiftCost");
                    if (item.GiftCost.HasValue)
                        tb.Text = item.GiftCost.Value.ToString("#,##0", new CultureInfo("en-US"));
                }
                else
                {
                    Label lbl = (Label)e.Row.FindControl("lblTourDate");
                    lbl.Text = item.TourDate;

                    Image img = (Image)e.Row.FindControl("imgTourDate");
                    if (item.IsConfirmed)
                        img.ImageUrl = ResolveClientUrl("~") + "images/bullet_ball_green.png";
                    else if (item.IsPending)
                        img.ImageUrl = ResolveClientUrl("~") + "images/bullet_ball_yellow.png";
                    else if (item.IsCanceled)
                        img.ImageUrl = ResolveClientUrl("~") + "images/bullet_ball_red.png";
                    else
                        img.Visible = false;

                    lbl = (Label)e.Row.FindControl("lblTourHotelCost");
                    if (item.TourHotelCost.HasValue)
                        lbl.Text = item.TourHotelCost.Value.ToString("$#,##0");

                    lbl = (Label)e.Row.FindControl("lblUpgradeFee");
                    if (item.UpgradeFee.HasValue)
                        lbl.Text = item.UpgradeFee.Value.ToString("$#,##0");

                    lbl = (Label)e.Row.FindControl("lblGiftCost");
                    if (item.GiftCost.HasValue)
                        lbl.Text = item.GiftCost.Value.ToString("$#,##0");
                }
                
                /*Tour item = (Tour)e.Row.DataItem;

                ImageButton ibtn = (ImageButton)e.Row.FindControl("lbtnDelete");
                ibtn.Visible = item.CanDelete;*/
            }
        }

        protected void grid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grid.EditIndex = -1;
            LoadData();
        }

        protected void grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            GridViewRow row = grid.Rows[e.RowIndex];
            int contactId = Convert.ToInt32(grid.DataKeys[e.RowIndex].Value);

            decimal? tourHotelCost = null;
            TextBox tb = (TextBox)row.FindControl("txtTourHotelCost");
            try
            {
                if (!string.IsNullOrEmpty(tb.Text))
                    tourHotelCost = decimal.Parse(tb.Text, new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Tour Hotel Cost not valid!'); }, 150);", true);
                return;
            }

            int? upgradeFee = null;
            tb = (TextBox)row.FindControl("txtUpgradeFee");
            try
            {
                if (!string.IsNullOrEmpty(tb.Text))
                    upgradeFee = int.Parse(tb.Text, new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Upgrade fee not valid!'); }, 150);", true);
                return;
            }

            int? giftCost = null;
            tb = (TextBox)row.FindControl("txtGiftCost");
            try
            {
                if (!string.IsNullOrEmpty(tb.Text))
                    giftCost = int.Parse(tb.Text, new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Gift cost not valid!'); }, 150);", true);
                return;
            }

            Contact itm = new Contact();
            itm.ContactId = contactId;
            itm.TourDate = ((TextBox)row.FindControl("txtTourDate")).Text;
            itm.TourTime = ((TextBox)row.FindControl("txtTourTime")).Text;
            DropDownList ddl = (DropDownList)row.FindControl("ddlTourCompany");
            itm.TourCompanyId = ddl.SelectedValue == "-1" ? (int?)null : Convert.ToInt32(ddl.SelectedValue);
            ddl = (DropDownList)row.FindControl("ddlTour");
            itm.TourHotelId = ddl.SelectedValue == "-1" ? (int?)null : Convert.ToInt32(ddl.SelectedValue);
            itm.TourHotelCost = tourHotelCost;
            itm.Verified = ((TextBox)row.FindControl("txtVerified")).Text;
            itm.VerificationsSend = ((TextBox)row.FindControl("txtVerificationsSend")).Text;
            itm.TourNotes = ((TextBox)row.FindControl("txtTourNotes")).Text;
            itm.ConfirmationNumber = ((TextBox)row.FindControl("txtConfirmationNumber")).Text;
            itm.UpgradeFee = upgradeFee;
            itm.Gift = ((TextBox)row.FindControl("txtGift")).Text;
            itm.GiftCost = giftCost;
            itm.Comments = ((TextBox)row.FindControl("txtComments")).Text;
            
            using (var repo = RepositoryFactory.ResolveRepository<ContactRepository>())
            {
                repo.UpdateTour(itm);
            }

            grid.EditIndex = -1;
            LoadDataFromDb();
            LoadData();
        }

        protected void grid_RowEditing(object sender, GridViewEditEventArgs e)
        {
            grid.EditIndex = e.NewEditIndex;
            LoadData();
        }

        protected void btnExcelExport_Click(object sender, EventArgs e)
        {
            List<Contact> data = GridViewData;
            string pageName = "Tour";
            List<string> headers = new List<string>();
            for (int i = 1; i < grid.Columns.Count; ++i)
            {
                headers.Add(grid.Columns[i].HeaderText);
            }
            List<string> fields = new List<string>();
            fields.AddRange(new string[] { "FullName", "TourDate", "TourTime", "TourCompanyName", "TourName", "TourHotelCost", "Verified", "VerificationsSend", "TourNotes", "ConfirmationNumber", "UpgradeFee", "Gift", "GiftCost", "Comments" });
            List<string> format = new List<string>();
            format.AddRange(new string[] { "", "", "", "", "#,##0.00", "", "", "", "", "", "#,##0", "", "#,##0", "" });

            ExcelPackage pck = Common.DataToExcel(data.Cast<object>().ToList(), headers, fields, format, pageName);

            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;  filename=" + pageName + ".xlsx");
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.BinaryWrite(pck.GetAsByteArray());
            Response.End();
        }

        protected void ddlPageSizeFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            string size = ddlPageSizeFilter.SelectedItem.Text;
            grid.AllowPaging = (size != "All");
            if (grid.AllowPaging)
            {
                grid.PageSize = Convert.ToInt32(size);
            }
            grid.PageIndex = 0;
            LoadData();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            LoadDataFromDb();
            LoadData();
        }
    }
}